import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { forkJoin } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd/message';
import { GoodsPublicnoteService } from './goods-publicnote.service';
import { PermissionService } from '../../../service/permission.service';

declare var UE: any;
@Component({
  selector: 'app-goods-publicnote',
  templateUrl: './goods-publicnote.component.html',
  styleUrls: ['./goods-publicnote.component.scss']
})
export class GoodsPublicnoteComponent implements OnInit {

  tableParams = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: any = [];

  /**
   * Modal
   * ---------------------------------------------------------------
   */
  isVisible: boolean = false;
  modalType: number = 0; // 0：新增，1：编辑
  modalItem: any = {};
  myeditor: any = null;
  validateForm!: FormGroup;
  uploadLoading: boolean = false;
  submitLoading: boolean = false;
  isEditorLoad: boolean = false;

  constructor(
    private fb: FormBuilder,
    private notification: NzNotificationService,
    private services: GoodsPublicnoteService,
    private message: NzMessageService,
    public permission: PermissionService,
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      noteName: ['', [Validators.required]],
      noteInfo: ['']
    });

    this.loadTable();
  }

  ngOnDestroy() {
    this.myeditor.destroy();
  }

  async loadTable() {
    let params = {
      current: this.tableParams.page,
      size: this.tableParams.pageSize
    }
    this.tableParams.tableLoading = true;
    const res: any = await this.services.getTableList(params);
    this.tableParams.tableLoading = false;

    if (res.code == 0) {
      const { records, total } = res.data || {};
      this.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  // 删除
  async delateData(item: any) {
    const res: any = await this.services.deleteItemData(item.id);
    if (res.code == 0) {
      this.message.success('删除成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * 新增 | 编辑
   * ----------------------------------------------------------------
   */
  showModal(num: number, item?: any) {
    this.modalType = num;

    if (item) {
      this.modalItem = item;
    }
    this.isVisible = true;
  }
  openModal() {
    this.isEditorLoad = true;
    this.myeditor = UE.getEditor('editorContent', {
      initialFrameWidth: 418,
      initialFrameHeight: 498,
      toolbars: [[]],
      elementPathEnabled: false,
      autoHeightEnabled: false,
      wordCount: false
    });

    setTimeout(() => {
      if (this.modalType == 1) {
        this.validateForm.patchValue({
          noteName: this.modalItem.noteName,
          noteInfo: this.modalItem.noteInfo || ''
        });
        
        if (this.modalItem.noteInfo) {
          this.myeditor.setContent(this.modalItem.noteInfo);
        }
      }
      this.isEditorLoad = false;
    }, 100)
  }
  handleCancel() {
    this.myeditor.destroy();
    this.validateForm.reset();
    this.isVisible = false;
  }
  submitForm() {
    if (this.validateForm.valid) {
      this.subInterface();
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
  async subInterface() {
    let htmlContent = this.myeditor.getContent();
    this.validateForm.get('noteInfo')?.setValue(htmlContent);

    let params = {
      ...this.validateForm.value
    }

    if (this.modalType == 1) {
      params.id = this.modalItem.id
    }
    this.submitLoading = true;
    let res: any;
    if (this.modalType == 0) {
      res = await this.services.addItemData(params);
    } else {
      res = await this.services.updateItemData(params);
    }

    this.submitLoading = false;
    if (res.code == 0) {
      this.message.success('操作成功');
      this.handleCancel();
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  // 上传图片
  async handleFileInput(files: any) {
    if (this.uploadLoading) {
      return
    }

    let file = files.target.files[0];
    this.uploadLoading = true;
    const res: any = await this.services.uploadImgData(file);
    this.uploadLoading = false;

    if (res.code == 0) {
      this.myeditor.execCommand("inserthtml", "<img style='max-width: 100%' src='" + res.data + "' />");
    } else {
      this.message.error(res.message);
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }
}
